﻿/* enc28j60_port.c */
#include "enc28j60.h"

#include "fsl_common.h"
#include "fsl_gpio.h"
//#include "fsl_lpspi.h"
#include "hal_lpspi.h"

void enc28j60_init_hardware(void)
{
    /* clock and pinmux are already setup with config tool. */

    /* spi0. */
    PCC->CLKCFG[PCC_LPSPI0_INDEX] = PCC_CLKCFG_CGC_MASK | PCC_CLKCFG_PCS(3U); /* Fast IRC. */

    LPSPI_MasterConfig_T lpspi_master_config;
    LPSPI_XferCommand_T lpspi_xfer_cmd;

    LPSPI_HAL_Reset(LPSPI0);
    LPSPI_HAL_Enable(LPSPI0, true);

    /* setup controller. */
    lpspi_master_config.enCSHigh = false;
    lpspi_master_config.TxFIFOWatermark = 1U;
    lpspi_master_config.RxFIFOWatermark = 0U;
    LPSPI_HAL_ConfigMaster(LPSPI0, &lpspi_master_config);

    /* setup transfer. */
    lpspi_xfer_cmd.PolPhaMode = eLPSPI_PolPhaMode0;
    lpspi_xfer_cmd.ClkDiv = eLPSPI_ClkDiv_8;
    lpspi_xfer_cmd.WhichCS = 0u;
    lpspi_xfer_cmd.enLSB = false;
    lpspi_xfer_cmd.enByteSwap = false;
    lpspi_xfer_cmd.enKeepCS = false;
    lpspi_xfer_cmd.DataBitsPerCmd = 8u;
    /* Set the xfer command. */
    LPSPI_HAL_SetXferCommand(LPSPI0, &lpspi_xfer_cmd);

#if 0
    lpspi_master_config_t lpspi_master_config;

    LPSPI_MasterGetDefaultConfig(&lpspi_master_config);
    lpspi_master_config.baudRate = 2000000u; /* 2M bps. */
    LPSPI_MasterInit(LPSPI0, &lpspi_master_config, CLOCK_GetIpFreq(kCLOCK_Lpspi0));
#endif

    /* gpio for cs. */
    gpio_pin_config_t gpio_pin_config;

    gpio_pin_config.pinDirection = kGPIO_DigitalOutput;
    gpio_pin_config.outputLogic = 1u;
    GPIO_PinInit(GPIOA, 10u, &gpio_pin_config);
}

void ENC28J60_CSL(void)
{
    GPIO_PinWrite(GPIOA, 10u, 0u);
}

void ENC28J60_CSH(void)
{
    GPIO_PinWrite(GPIOA, 10u, 1u);
}

unsigned char enc28j60_spi_hw_send_byte(unsigned char dat)
{
    uint8_t tmp8;

    /* Fill the data into Tx FIFO. */
    while (LPSPI_FLAG_TX_DONE_MASK != LPSPI_HAL_GetStatus(LPSPI0, LPSPI_FLAG_TX_DONE_MASK))
    {}
    LPSPI_HAL_SetTxData(LPSPI0, dat);

    /* Get the data from Rx FIFO. */
    while (LPSPI_FLAG_RX_DONE_MASK != LPSPI_HAL_GetStatus(LPSPI0, LPSPI_FLAG_RX_DONE_MASK))
    {}
    tmp8 = (uint8_t)LPSPI_HAL_GetRxData(LPSPI0);

    /* wait the tx fifo is empty. */
    while (LPSPI_FLAG_XFER_DONE_MASK != LPSPI_HAL_GetStatus(LPSPI0, LPSPI_FLAG_XFER_DONE_MASK) )
    {}

    return tmp8;
}

/* EOF. */

